/*
 *  Copyright (C) 2010 Glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.swing.components.util;

import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import javax.swing.JPanel;
import org.balisunrise.common.EntityFilter;
import org.balisunrise.common.EntityLoader;
import org.balisunrise.common.FieldComponent;
import org.balisunrise.common.FieldLayout;

/**
 *
 * @author Glauco
 */
public class EntityFilterFocusTraversal implements FocusTraversalListener{

    EntityFilter<JPanel> ef;
    EntityLoader entityLoader;
    JPanel panel;

    public EntityFilterFocusTraversal(EntityFilter<JPanel> ef) {
        this.ef = ef;
        entityLoader = ef.getEntityLoader();
        panel = ef.getVisualRepresentation();
    }

    /**
     * Verifica se o focus passou por algum componente do EntityFilter e
     * dispara a atualização.
     *
     * @param activeContainer
     * @param ftp
     * @param oldComponent
     * @param newComponent
     * @param lastComponet
     */
    public void checkFocusTraversal(Container activeContainer,
            FocusTraversalPolicy ftp, Component oldComponent,
            Component newComponent, Component lastComponet) {

        // retorna se os componentes forem de janelas diferentes
        // ou o container ativo for nulo ou não ter focusTravelPolice
        if(oldComponent.getFocusCycleRootAncestor() !=
                          panel.getFocusCycleRootAncestor() ||
                ftp == null){

            return ;
        }
        for (FieldLayout fl : ef.getFieldLayouts()) {
            for (FieldComponent fc : fl.getFieldComponents()) {
                if(fc.getVisualRepresentation().equals(oldComponent)){
                    fire();
                    return ;
                }
            }
        }
    }

    private void fire(){
        if (entityLoader != null && ef.isModified())
            entityLoader.load(ef.getQuery());
    }
}
